package tech.aistar.day02;

import com.alibaba.fastjson.JSONArray;
import tech.aistar.pojo.Result;
import tech.aistar.pojo.User;
import tech.aistar.service.IUserService;
import tech.aistar.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 本类用来演示:java对象转换成json格式[前后端数据交互的一种格式]
 *
 * @author: success
 * @date: 2021/4/16 3:34 下午
 */
@WebServlet(urlPatterns = "/json")
public class JsonDemo extends HttpServlet {

    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 设置文档输出类型
        resp.setContentType("application/json;charset=utf-8");

        PrintWriter out = resp.getWriter();

        //User user = userService.login("admin");

        List<User> users = userService.loadAll();

        //定义统一返回的json对象
        Result result = new Result("200","查询所有用户",users);

        String str = JSONArray.toJSONString(result);

        //返回数据..
        out.print(str);
    }
}
